package com.wss.lsl.test.driven.part1;

import java.util.Stack;

/**
 * 有序链表
 * 
 * @author Administrator
 * 
 */
public class IntSetList {

	private Node head;
	private int size = 0;

	public void insert(int val) {
		head = rinsert(val);
		size++;
	}

	/**
	 * 消除递归
	 * 
	 * @param val
	 * @return
	 */
	private Node rinsert(int val) {
		Node h = head;
		Stack<Node> stack = new Stack<Node>();
		while (true) {
			if (h == null) {
				h = new Node(val, null);
				if (!stack.isEmpty()) {
					Node temp = stack.peek();
					temp.next = h;
				}
				stack.push(h);
				break;
			}
			if (h.val < val) {
				stack.push(h);
				h = h.next;
				continue;
			} else {
				h = new Node(val, h);
				if (!stack.isEmpty()) {
					Node temp = stack.peek();
					temp.next = h;
				}
				stack.push(h);
				break;
			}
		}
		return stack.firstElement();
	}

	/**
	 * 返回复制链表
	 * 
	 * @return
	 */
	public Node getList() {
		Node tHead = null;
		if (head != null) {
			Node tTemp = new Node(head.val, null);
			tHead = tTemp;
			Node temp = head.next;
			while (temp != null) {
				Node node = new Node(temp.val, null);
				tTemp.next = node;
				tTemp = node;
				temp = temp.next;
			}
		}
		return tHead;
	}

	public int size() {
		return size;
	}
}
